<template>
  <view class="address_lists_box">
    <block v-if="addressListArray.length > 0">
      <view class="address" :class="isIpx ? 'fix-iphonex' : ''">
        <view v-for="(item, index) in addressListArray" :key="index" style="margin-top: 16rpx;">
          <delSlideLeft :item="item" :data_transit="{index:index,id:item.customerAddressId}" @delItem="handleDelItem"
            @moveItem="handelMoveItem">
            <view class="list_box">
              <view class="address_list" @click.stop="tapSelAddress" :data-id="item.customerAddressId">
                <view class="title">
                  <view class="address-block">
                    <view class="user_info">
                      {{item.receiverName | filterName}}&nbsp;&nbsp;&nbsp;&nbsp;{{ item.receiverMobile }}
                    </view>
                    <view class="active_address">{{ item.receiverState }} {{ item.receiverCity }}
                      {{ item.receiverDistrict }} {{ item.receiverTown }} {{ item.receiverAddress }}
                    </view>
                    <text class="defult" v-if="item.isDefault == 1">默认地址</text>
                  </view>
                  <view :class="item.isDefault == 1? 'arrowDefault' : 'arrow'" @click.stop="handelEdit"
                    :data-id="item.customerAddressId">
                    编辑
                  </view>
                </view>
              </view>
            </view>
          </delSlideLeft>
        </view>
      </view>
      <view class="add_wrap-box">
        <view class="add_wrap" @click="handelAdd">新增收货地址</view>
      </view>
    </block>
    <block v-else>
      <view class="empty_list_box">
        <image class="empty_img" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/empty_cart_logo4x.png" />
        <view class="empty_text">暂无地址</view>
        <view class="bottom_box">
          <view class="weixin_get_address" @click="getAddress">
            <view class="qAdd_text">授权微信地址</view>
          </view>
          <view class="empty_btn" @click="handelAdd">新增收货地址</view>
        </view>
      </view>
    </block>
    <checkDialog v-if="dialog" :address='address' @closeDialog='closeDialog' @checkIn='checkIn'></checkDialog>
    <districtDialog v-if="district" @closeDistrictDialog='closeDistrictDialog'></districtDialog>
    <completeStreet v-if="showStreetDialog" operateHandle='select' @closeStreetDialog='closeStreetDialog'></completeStreet>
		<!-- 弱提示 弹窗 -->		
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
		
  </view>
</template>
<script>
  import api from '@/api/api';
  import checkDialog from './drawCheckDialog.vue';
  import districtDialog from './districtDialog.vue';
	
  import {
    USER_SPECICAL_INFO,
    ADDRESS_ID,
    CUSTOMER_INFO,
    MERCHANT_INFO
  } from '@/utils/constant';
  import delSlideLeft from '@/pages/ay-operate/del_slideLeft.vue'
  // import completeStreet from '@/components/completeStreet/completeStreet.vue'
  import completeStreet from './completeStreet.vue';
  export default {
    props: {
      addressListArray: {
        type: Array
      },
      checkIndex: {
        type: Number
      },
      skuIdArr: {
        type: Array
      },
    },
    components: {
      delSlideLeft,
      checkDialog,
      districtDialog,
      completeStreet,
    },
    data() {
      return {
        receiverInfo: {},
        type: '',
        isIpx: false,
        address: {},
        dialog: false,
        addressId: '',
        district: false,
        showStreetDialog: false,
      };
    },
    filters:{
      filterName(val){
        let name ;
        if(val.length>10){
          name = val.substring(0,10) +'...'
        } else {
          name = val
        }
        return name
      }
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){
				const {type, callBackData} = data;
				if(type === 'confirm'){
					//	地址删除
					if(callBackData && callBackData.type === 'delUserAddress' && callBackData.data){
						this.delUserAddress(callBackData.data);
					}
				}
			},
      delUserAddress: async function(id) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const json = await api.delUserAddress({
            method: 'DELETE',
            header: {
              jwt: customerInfo.jwt
            }
          },
          customerInfo.customerId,
          id
        );
        if (json.code === 1000) {
          uni.removeStorageSync('addressId');
          if (this.type == 'gift') {
            this.$emit('currentPage', 0);
            this.$parent.getUserAddress('', true);
            return
          }
          this.$emit('currentPage', 0);
          this.$parent.getUserAddress();
        } else {
					this.handleShowTextToast(json.msg);
        }
        that.showLoading = false;
      },
      handelAdd() {
        //0 列表 1新增 2编辑
        this.$emit('currentPage', 1);
        this.$emit('changShowGetAddress', false)
        //新增地址埋点
        let clTrackPrams = {
          'c_area': '地址管理-新增收货地址'
        }
        getApp().commonClTrack('c_ebmp_setup_click', clTrackPrams)
      },
      handelEdit(e) {
        let that = this;
        uni.vibrateShort({
          complete(res) {
            let id = e.currentTarget.dataset.id;
            //0 列表 1新增 2编辑 向父组件发射页面id和地址id
            that.$emit('currentPage', 2, id,true);
          }
        });
        //编辑地址埋点
        let clTrackPrams = {
          'c_area': '地址管理-编辑收货地址'
        }
        getApp().commonClTrack('c_ebmp_setup_click', clTrackPrams)
      },
      //地址删除
      async handleDelItem(e) {
				this.$refs.toastPopup.showPopup({
					msg:"确认删除吗？",
					callBackData: {
						type: "delUserAddress",
						data: e.data.id
					}})
      },
      handelMoveItem(e) {
        this.$emit('moveAddressItem', e);
      },

      refreshList(val) {
        if (val === undefined) return;
        this.addressListArray = val;
      },
      setOrgType(type) {
        this.type = type;
      },
      chooseAddress(id) {
        if (this.type == 'order') {
          this.bindAddressId(id, this.type);
        } else {
          uni.setStorageSync(ADDRESS_ID, id);
          uni.navigateBack();
        }
      },
      // 监听订单页面过来选择地址id
	  // 添加判断订单地址修改
      tapSelAddress(e) {
		 let id = e.currentTarget.dataset.id;
        if (this.type == 'order' || this.type == 'draw' || this.type == 'gift' ) {
          if (uni.getStorageSync('cartKey') !== null) {
           
            this.bindAddressId(id, this.type);
          }
        }
		if(this.type == 'reSet' ) {
			if (uni.getStorageSync('cartKey') !== null) {
					this.$emit('reSetAddModel', ()=>{   this.$emit('reSetAddressId', id); });
			}
		}
      },
      bindAddressId: async function(id, type) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        let jwt = customerInfo.jwt;
        let pages = getCurrentPages();
        let cartKey = uni.getStorageSync('cartKey')
        if (type !== 'draw' && type !== 'gift') {
          if (pages[pages.length - 3]?.route == "pages/item/item") {
            cartKey = uni.getStorageSync('buyNowCartKey') || uni.getStorageSync('cartKey')
          }
        }
        // 获取顾客地址信息
        const json = await api.setOrderAddressIdNew({
            method: 'PUT',
            header: {
              jwt: jwt
            }
          },
          cartKey,
          id
        );
        if (json.code === 1000) {
          uni.setStorageSync(ADDRESS_ID, id);
          if (type !== 'draw' && type !== 'gift') {
            uni.navigateBack();
          } else {
            this.getAddressInfo(id, type)
          }
        }
      },
      getAddressInfo: async function(id, type) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let customerId = customerInfo.customerId;
        let jwt = customerInfo.jwt;

        // 获取顾客地址信息
        const json = await api.getAddressInfoById({
            header: {
              jwt: jwt
            }
          },
          customerId,
          id
        );
        if (json.code === 1000) {
          this.address = json.data;
          this.addressId = id
          let noStreetDistict = ['东莞市','中山市','儋州市']
          let noStreet = noStreetDistict.indexOf(json.data.receiverCity)
          if (!!json.data && !json.data.receiverTown && noStreet == -1) {
            this.showStreetDialog = true
            return false
          }
          if (type == 'draw') {
            this.checkDistrict(id)
          } else if (type == 'gift') {
            this.$emit('setDeafaultAddress', {info: json.data, type:'list'})
          }

        }
      },
      closeStreetDialog(){
        this.showStreetDialog = false
        this.$emit('currentPage', 2, this.addressId,'drawStreet');
      },
      closeDialog() {
        this.dialog = false
        this.$commonSensors.popupEvent('PopupClick', {'popup_type' : '购买', 'popup_name': '确认登记信息弹窗', 'button_name': '取消'})
      },
      checkIn() {
        this.$parent.checkIn(this.addressId)
      },
      // 检测地区是否可以配送
      async checkDistrict(id) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
        const json = await api.checkDistrict({
          method: 'POST',
          header: {
            jwt: customerInfo.jwt
          },
          query: {
            storeId: merchantInfo.cloudMerchantStoreId,
            skuIds: this.skuIdArr,
            customerAddressId: id
          }
        })
        if (json.code == 1000) {
          this.$parent.checkDrawDistrict(this.addressId, 'list')
        } else {
          this.district = true
        }
      },
      openDialog() {
        this.dialog = true
        this.district = false
        this.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '购买', 'popup_name': '确认登记信息弹窗'})
      },
      openDistrictDialog() {
        this.district = true
        this.dialog = false
      },
      closeDistrictDialog() {
        this.district = false
        this.dialog = false
      },
      //  授权获取微信地址
      getAddress() {
        let that = this;
        uni.getSetting({
          success(res) {
            if (res.authSetting['scope.address']) {
              uni.chooseAddress({
                success(res) {
                  that.setDefaultAddress(res);
                }
              });
              // 用户已经同意小程序使用录音功能，后续调用 uni.startRecord 接口不会弹窗询问
            } else {
              if (res.authSetting['scope.address'] == false) {
                uni.openSetting({
                  success(res) {
               
                  }
                });
              } else {
                uni.chooseAddress({
                  success(res) {
                    that.setDefaultAddress(res);
                  }
                });
              }
            }
          }
        });
      },
      //  微信授权地址格式化
      setDefaultAddress(address) {
        try{
          let defaultAddress = {};
          let datalist = [];
          defaultAddress.receiverName = address.userName;
          defaultAddress.mobile = address.telNumber;
          defaultAddress.addressDetail = address.detailInfoNew || address.detailInfo;
          if(address.nationalCode.slice(0, 4) == '4419' || address.nationalCode.slice(0, 4) == '4420' || address.nationalCode.slice(0, 4) == '4604' ) {
            datalist = [{
              'areaCode': address.nationalCode.slice(0, 2) + '0000000',
              'areaName': address.provinceName,
              'areaType': "state",
              'parentCode': "000000000"
            }, {
              'areaCode': address.nationalCode.slice(0, 4) + '00000',
              'areaName': address.cityName,
              'areaType': "city",
              'parentCode': address.nationalCode.slice(0, 2) + '0000000'
            }, {
              'areaCode': address.nationalCodeFull,
              'areaName': address.countyName,
              'areaType': "district",
              'parentCode': address.nationalCode.slice(0, 4) + '00000'
            }]
          } else {
            datalist = [{
              'areaCode': address.nationalCode.slice(0, 2) + '0000000',
              'areaName': address.provinceName,
              'areaType': "state",
              'parentCode': "000000000"
            }, {
              'areaCode': address.nationalCode.slice(0, 4) + '00000',
              'areaName': address.cityName,
              'areaType': "city",
              'parentCode': address.nationalCode.slice(0, 2) + '0000000'
            }, {
              'areaCode': address.nationalCode.slice(0, 6) + '000',
              'areaName': address.countyName,
              'areaType': "district",
              'parentCode': address.nationalCode.slice(0, 4) + '00000'
            }]
            if(address.streetName){
              datalist.push({
                'areaCode': address.nationalCodeFull,
                'areaName': address.streetName,
                'areaType': "town",
                'parentCode': address.nationalCode.slice(0, 6) + '000'
              })
            }else{
              datalist.push('请选择街道');
            }
          }
          this.checkWechatDaddress(defaultAddress,datalist)
        }catch(e){
          
        }
      },
      //  微信授权地址校验
      checkWechatDaddress(defaultAddress,datalist) {
        try{
          defaultAddress.receiverName = !!defaultAddress.receiverName ? defaultAddress.receiverName.trim() : defaultAddress.receiverName;
          defaultAddress.receiverName = defaultAddress.receiverName && defaultAddress.receiverName.replace(
            /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|[\uD800-\uDBFF]|[\uDC00-\uDFFF]|[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
            ''
          );
          defaultAddress.addressDetail = defaultAddress.addressDetail && defaultAddress.addressDetail
            .replace(
              /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|[\uD800-\uDBFF]|[\uDC00-\uDFFF]|[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
              ''
            );
          if (!defaultAddress.receiverName) {
						this.handleShowTextToast('输入收件人姓名');
            return false;
          }
          if (!defaultAddress.mobile) {
						this.handleShowTextToast('输入联系电话');
            return false;
          } else if (defaultAddress.mobile.length < 11) {
						this.handleShowTextToast('手机号长度有误');
            return false;
          }
          const myreg = /^(1[3|4|5|6|7|8|9])\d{9}$/;
          if (!myreg.test(defaultAddress.mobile)) {
						this.handleShowTextToast('手机号格式有误');
            return false;
          }

          if (datalist.length == 4 && typeof(datalist[3]) !== "object" || datalist.length == 3 && typeof(datalist[2]) !== "object") {
						this.handleShowTextToast('请完善所在地区');
            return false;
          }
          if (!defaultAddress.addressDetail) {
						this.handleShowTextToast('请输入详细地址信息');
            return false;
          }
          this.submitUserAddress(defaultAddress, datalist);
        }catch(e){
          
        }
      },
      //  新增地址信息
      async submitUserAddress(address, datalist) {
        try{
          let that = this;
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
          let isDefult = 0;
          let customerId = customerInfo.customerId;
          let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
          const json = await api.saveAddress({
              method: 'POST',
              header: {
                jwt: jwt
              },
              query: {
                customerId: customerId,
                receiverMobile: address.mobile,
                receiverName: address.receiverName,
                receiverAddress: address.addressDetail,
                isDefault: isDefult,
                receiverState: datalist[0].areaName,
                receiverCity: datalist[1].areaName,
                receiverDistrict: datalist[2].areaName,
                receiverTown: datalist.length > 3 ? datalist[3].areaName : '',
                areaCode: datalist.length > 3 ? datalist[3].areaCode : datalist[2].areaCode
              }
            },
            customerId
          );
          this.address = Object.assign({}, address)
          this.address.receiverState = datalist[0].areaName
          this.address.receiverCity = datalist[1].areaName
          this.address.receiverDistrict = datalist[2].areaName
          this.address.receiverTown = datalist.length > 3 ? datalist[3].areaName : ''
          this.address.receiverAddress = address.addressDetail
          this.address.receiverMobile = address.mobile
          this.address.receiverTown = datalist.length > 3 ? datalist[3].areaName : ''
          if (json.code === 1000) {
            this.addressId = json.data.customerAddressId
            uni.setStorageSync('addressId', json.data.customerAddressId);
            if (this.type == 'draw') {
              this.checkDistrict(json.data.customerAddressId)
              return false
            }
            if (!this.showAddList && this.type == 'gift') {
              //0 列表 1新增 2编辑 (显示列表)
              this.getAddressInfo(json.data.customerAddressId)
              return
            }
            this.$emit('currentPage', 0, json.data.customerAddressId);
          } else {
						this.handleShowTextToast(json.msg);
          }
        }catch(e){
          
        }
      },
    }
  };
</script>
<style lang="less">
  .address_lists_box{
    background: #fff;
    padding: 0 48rpx;
    width: 100%;
    font-family: FrankNew-Regular,NotoSansSC-Regular;
  }
  .address {
    padding-bottom: 200rpx;
    padding-top: 16rpx;

    .list_box {
      // margin-top: 16rpx;
    }

    .address_list {
      padding: 32rpx;
      background-color: #fafafa;
      .title {
        color: #000;
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
      .user_info {
        color: #000000;
        font-size: 28rpx;
        font-family: FrankNew-Medium,NotoSansSC-Medium;
        line-height: 48rpx;
      }
      .active_address {
        width: 100%;
        line-height: 48rpx;
        color: #000;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 24rpx;
      }
    }

    .defult {
      color: #CB171A;
      font-size: 24rpx;
    }
  }

  .arrow,
  .arrowDefault {
    color: #757575;
    padding-left: 70rpx;
    display: flex;
    align-items: center;
  }

  .add_wrap-box {
    width: 100%;
    background-color: #ffffff;
    left: 0;
    right: 0;
    position: fixed;
    bottom: 0;
    margin: 0 auto;
    padding-bottom: 30rpx;
    z-index: 5;
    padding: 0 48rpx 64rpx 48rpx;
  }

  .add_wrap {
    text-align: center;
    width: 654rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 48rpx 16rpx 48rpx 48rpx;
    font-size: 28rpx;
    color: #ffffff;
    background-color: #000;
		font-family: NotoSansSC-Medium;
  }

  .address_btnBox {
    display: flex;
    flex-direction: row-reverse;
  }

  .address_btnBox view {
    margin-left: 30rpx;
  }

  .address_btnBox .defult {
    flex-grow: 1;
  }

  .address-block {
    width: 468rpx;
  }

  page {
    background-color: #f9f9f9;
  }

  .fix-iphonex {
    padding-bottom: 160rpx;
  }

  .empty_list_box{
    padding-top: 256rpx;
  }
  .empty_img{
    width: 108.38rpx;
    height: 80rpx;
    display: block;
    margin: 0 auto;
  }
  .empty_text{
    width: 100%;
    line-height: 48rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: normal;
    font-family: NotoSansSC-Regular;
    margin-top: 80rpx;
  }
  .empty_btn{
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 48rpx 16rpx 48rpx 48rpx;
    background-color: #000;
    color: #fff;
    font-size: 28rpx;
    font-weight: 500;
    text-align: center;
    margin-top: 64rpx;
    font-family: NotoSansSC-Medium;
  }
  .weixin_get_address{
    width: 100%;
    text-align: center;
    font-family: NotoSansSC-Regular;
    font-size: 28rpx;
    font-weight: 500;
    color: #000;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .qAdd_text{
    border-bottom: 1px solid #000;
    padding-bottom: 6px;
    text-align: center;
    line-height: 1;
  }
  .bottom_box{
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 64rpx;
    padding: 0 48rpx;
  }
</style>
